import { prisma } from "../utils/prisma.sql.utils";
import { TransferDateFormatter } from "../utils/tranferDateFormatter";

export class UserService {
  /**
   * getAllUsers
   */
  async getAllUsers(): Promise<any | null> {
    let users = await prisma.user.findMany({
      where: { status: "active" },
    });

    if (!users || users.length === 0) {
      throw new Error("No users found");
    }
    TransferDateFormatter.transferDate(users);
    return users;
  }

  /**
   * 通过ID获取用户
   */
  async getUserByIdForProfile(id: string): Promise<any | null> {
    let user = await prisma.user.findUnique({
      where: { id: Number(id) },
    });
    TransferDateFormatter.transferDate(user);
    const blog_count: any =
      await prisma.$queryRaw`SELECT count(1) as blog_count  FROM blog WHERE user_id = ${id}`;
    return { ...user, blog_count: parseInt(blog_count[0].blog_count) };
  }
  async getUserById(id: string): Promise<any | null> {
    const user = await prisma.user.findUnique({
      where: { id: Number(id) },
    });
    TransferDateFormatter.transferDate(user);
    return user;
  }

  async updateUser(id: string, data: any): Promise<any | null> {
    console.log(data);
    return prisma.user.update({
      where: { id: Number(id) },
      data: data,
    });
  }

  async deleteUser(id: string): Promise<any | null> {
    return prisma.user.delete({
      where: { id: Number(id) },
    });
  }

  async usersForPage(
    page: number,
    pageSize: number,
    keyword: string | null
  ): Promise<any | null> {
    const skip = (page - 1) * pageSize;
    const take = pageSize;
    const keyword_clause = keyword
      ? {
          username: { contains: keyword },
        }
      : {};
    let users = await prisma.user.findMany({
      where: { status: "active", ...keyword_clause },
      skip,
      take,
    });
    const total = await prisma.user.count({
      where: { status: "active", ...keyword_clause },
    });
    TransferDateFormatter.transferDate(users);
    return { users, total };
  }
}
